/**
 * Copyright 2014-2020  the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.upb.webserver.account;

import com.upb.webserver.account.manager.ManagerService;
import com.upb.webserver.common.enums.AccountStatusEnum;
import com.upb.webserver.common.enums.PlatformEnum;
import com.upb.webserver.common.exception.WebServerException;
import com.upb.webserver.common.pojo.account.AccountCommon;
import com.upb.webserver.common.pojo.login.LoginAccount;
import com.upb.webserver.common.returncode.ConstantCode;
import com.upb.webserver.common.tools.JsonUtils;
import com.upb.webserver.common.tools.WebServerTools;
import com.upb.webserver.dao.entity.TbDeveloper;
import com.upb.webserver.dao.entity.TbManager;
import com.upb.webserver.dao.entity.TbRole;
import com.upb.webserver.dao.mapper.TbDeveloperMapper;
import com.upb.webserver.dao.mapper.TbManagerMapper;
import com.upb.webserver.dao.mapper.TbRoleMapper;
import com.upb.webserver.token.TokenService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;

/**
 * services for account data.
 */
@Log4j2
@Service
public class AccountService {
    @Autowired
    private TbDeveloperMapper developerMapper;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private TbManagerMapper managerMapper;
    @Autowired
    private TbRoleMapper roleMapper;
    @Autowired
    private TokenService tokenService;


    /**
     * @param request
     * @return
     */
    public AccountCommon getAccountCommon(HttpServletRequest request) {
        //get current user
        String token = WebServerTools.getToken(request);
        AccountCommon currentAccount = this.getAccountCommon(tokenService.getValueFromToken(token));
        return currentAccount;
    }


    /**
     * @param loginAccountJsonBase64
     * @return
     */
    public AccountCommon getAccountCommon(String loginAccountJsonBase64) {
        log.debug("start exec method [getAccountCommon]. loginAccountJsonBase64:{}", loginAccountJsonBase64);

        String accountJson = new String(Base64.getDecoder().decode(loginAccountJsonBase64), StandardCharsets.UTF_8);
        LoginAccount loginAccount = JsonUtils.stringToObj(accountJson, LoginAccount.class);
        AccountCommon obj;
        if (PlatformEnum.DEVELOPER.getId() == loginAccount.getPlatform()) {
            TbDeveloper developerRow = developerMapper.selectByAccount(loginAccount.getAccount());
            if (developerRow != null && AccountStatusEnum.FREEZE.getId() == developerRow.getStatus()) {
                throw new WebServerException(ConstantCode.ACCOUNT_HAD_BEAN_FREEZE);
            }
            obj = AccountCommon.builder().setDeveloper(developerRow).build();
        } else if (Arrays.asList(PlatformEnum.DEV_OPS.getId(), PlatformEnum.AUDIT.getId()).contains(loginAccount.getPlatform())) {
            TbManager managerRow = managerService.getByPlatformAndAccount(loginAccount.getPlatform(), loginAccount.getAccount());
            obj = AccountCommon.builder().setManagerRow(managerRow).build();
        } else {
            throw new RuntimeException("not support this platform");
        }

        //role
        TbRole tbRole = roleMapper.selectByPrimaryKey(obj.getRoleId());
        obj.setPlatform(loginAccount.getPlatform());
        obj.setRoleName(tbRole.getName());

        log.debug("success exec method [getAccountCommon]. result:{}", JsonUtils.objToString(obj));
        return obj;
    }


    /**
     * @param platform
     * @param accountId
     * @return
     */
    public String getAccountNameById(Byte platform, int accountId) {
        log.debug("start exec method [getAccountById]. platform:{} accountId:{}", platform, accountId);
        if (PlatformEnum.DEV_OPS.getId() == platform) {
            TbManager managerRow = managerMapper.selectByPrimaryKey(accountId);
            return managerRow == null ? null : managerRow.getAccount();
        }
        if (PlatformEnum.DEVELOPER.getId() == platform) {
            TbDeveloper developerRow = developerMapper.selectByPrimaryKey(accountId);
            return developerRow == null ? null : developerRow.getAccount();
        }
        log.warn("not support platform:{}", platform);
        return null;
    }
}
